package com.ming.closeto.ui;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;

import com.ming.closeto.base.BasePermissionActivity;
import com.ming.closeto.MainActivity;
import com.ming.closeto.R;
import com.ming.closeto.entity.Constant;
import com.ming.closeto.listener.OnRequestPermissionListener;
import com.ming.closeto.utils.SharedPreUtils;
import com.ming.closeto.utils.VersionUtils;

public class IndexActivity extends BasePermissionActivity {

    private String [] mStrPermission =
            {Manifest.permission.CALL_PHONE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.CAMERA};


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case Constant.H_TO_MAIN:
                    // 判断进入哪个页面
                    if (isFirstRunApp()) {
                        startActivity(new Intent(IndexActivity.this, MainActivity.class));
                    } else {
                        startActivity(new Intent(IndexActivity.this, GuideActivity.class));
                    }
                    finish();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_index);

        initView();
    }

    private void initView() {
        // 申请权限
        if (VersionUtils.isM()) {
            checkPermissions(mStrPermission, 100, new OnRequestPermissionListener() {
                @Override
                public void onSuccessful(int[] grantResults) {
                    mHandler.sendEmptyMessageDelayed(Constant.H_TO_MAIN, 1500);
                }

                @Override
                public void onFailure() {
                    mHandler.sendEmptyMessageDelayed(Constant.H_TO_MAIN, 1500);
                }

            });
        } else {
            mHandler.sendEmptyMessageDelayed(Constant.H_TO_MAIN,1500);
        }
    }

    // 判断是否第一次运行
    private boolean isFirstRunApp() {
        boolean isFirst = SharedPreUtils.getBoolean(this, "isFirst", false);
        // 第一次运行 为false
        if (isFirst) {
            return true;
        } else {
            SharedPreUtils.putBoolean(this, "isFirst", true);
            return false;
        }
    }

    // 禁止返回键
    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }
}
